﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DTO;
using System.IO;
using BUS;
using System.Xml;
using System.Data.SqlClient;
namespace GPBenhLanh
{
    public partial class frmKQTeBaoPAP : DevExpress.XtraEditors.XtraForm
    {
        public frmKQTeBaoPAP()
        {
            InitializeComponent();
            initControl(this);
            ByTB = 1;
        }

        public frmKQTeBaoPAP(TTXacNhanDTO xnf)
        {
            InitializeComponent();
            Xn = xnf;
            initControl(this);
        }

        TTXacNhanDTO _xn;
        public TTXacNhanDTO Xn
        {
            get { return _xn; }
            set { _xn = value; }
        }

        private TTKetQuaPAPDTO kqPAP = new TTKetQuaPAPDTO();

        string _sThuMucLuu;
        public string sThuMucLuu
        {
            get { return _sThuMucLuu; }
            set { _sThuMucLuu = value; }
        }
        //1: nhập kết quả theo số tiêu bản
        //0: nhâp kết quả theo cách truyền thống
        private int ByTB = 0;

        private Bitmap bmHinh1 = null;
        private Bitmap bmHinh2 = null;
        private Bitmap bmHinh3 = null;
        private Bitmap bmHinh4 = null;
        private int ketqua = 0;
        private int flagLuu = 1;
        private int flagKQ = 0;
        private int lan = 0;
        private DateTime cDate = DateTime.Today;//ngay xac nha cua ket qua
        //dataTran[0]: lan ; dataTran[1]: 1=reload 0=No reload
        private int[] dataTran = new int[4];
        private static string strPathHinh = "";
        public void getPathStrHinh()
        {
            string _sConnection = Uit.it_Conn.getConnectString("pathStrHinh");
            strPathHinh = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public delegate void MyDelege2(object sender, Object data);
        public event MyDelege2 thoatEven;

        private int[] isImg= new int[4]{0,0,0,0};

        private void initControl(Control ctrl)
        {

            // Bỏ qua điều kiểm trừ khi nó là TextBox.
            if (ctrl.Tag == "text")
            {
                ctrl.Text = "";
            }

            // Xử lý các điều kiểm một cách đệ quy.
            // Điều này cần thiết khi có một điều kiểm chứa nhiều 
            // điều kiểm khác (ví dụ, khi bạn sử dụng Panel, 
            // GroupBox, hoặc điều kiểm container nào khác).
            foreach (Control ctrlChild in ctrl.Controls)
            {
                initControl(ctrlChild);
            }
        }
        public static string _strConnectPK;
        SqlConnection conpk;

        /// <summary>
        /// get thong tin ket noi den database phKham
        /// </summary>
        public void getConnectStringPK()
        {
            string _sConnection = Uit.it_Conn.getConnectString("ConnectPhkham");
            _strConnectPK = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        public void CnPKham()
        {
            if (conpk == null || conpk.State == ConnectionState.Closed)
            {
                getConnectStringPK();
                conpk = new SqlConnection();
                conpk = Uit.it_Conn.getConnect(_strConnectPK);
            }
        }
        private void loadComboBox()
        {
            DataTable dtbs = GetThongTinSearchBUS.SearchDSBacSi();
            comBacSi.Properties.DataSource = dtbs;
            comKTV.Properties.DataSource = GetThongTinSearchBUS.SearchDSKTV();
            //comBacSi.EditValue = 267;
            comKTV.EditValue = 1;
            comPTVien.Properties.DataSource = GetThongTinSearchBUS.SearchDSBacSiCD();

            comDonVi.Properties.DataSource = GetThongTinSearchBUS.SearchDonVi(conpk);
            
        }

        private void loadTTHC()
        {
            //set thong tin hanh chinh cua benh nha
            txtHoTen.Text = Xn.HoTen;
            int Tuoi = DateTime.Today.Year - Convert.ToInt32(Xn.NamSinh);
            txtTuoi.Text = Xn.NamSinh.ToString();
            if (Xn.Gioi == true)
                txtGioi.Text = "Nam";
            else
                txtGioi.Text = "Nữ";
            txtNghe.Text = Xn.DienThoai;
            txtSoHS.Text = Xn.SoHS;
            txtSoBN.Text = Xn.SoBN;
            txtDichVu.Text = Xn.TenDVu;
            txtSoNVien.Text = Xn.SoNV;
            txtDVChiDinh.Text = comDonVi.Text;
            txtChuanDoan.Text = Xn.ChuanDoan;
            loadComboBox();
            txtsotieuban.Text = Xn.SoTieuBan;
            lblLoaiBN.Text = Xn.LoaiBN.ToString();
            lblDVCode.Text = Xn.DVuCode;
        }
                
        private void loadKQ()
        {
          
            //load lai kq
            DataTable dt = KQBUS.GetKetQuaPAP(txtSoBN.Text, txtSoHS.Text);
            DataTable dtListBenh = GetThongTinSearchBUS.GetDsBenhPAP();
            
            if (dt.Rows.Count > 0)//da co kq
            {
                comBacSi.EditValue = int.Parse(dt.Rows[0]["IDBacSiTH"].ToString());
                combscd.EditValue = Xn.IDBacSiCD;
                comKTV.EditValue = int.Parse(dt.Rows[0]["IDKTV"].ToString());
                txtsotieuban.Text = dt.Rows[0]["SoTieuBan"].ToString();
             
                //neu da co ket qua
                if (dt.Rows[0]["KetLuan"].ToString() != "")
                {
                    //pnlKQ.Enabled = false;
                    //cDate = DateTime.Parse(dt.Rows[0]["CDate"].ToString());
                    //int ss = DateTime.Compare(cDate, DateTime.Today);
                    //if (ss < 0)//qua ngay
                    //{
                    //    ptnButtonLXS.Enabled = false;
                    //    btnChupHinh.Enabled = false;
                    //    btnSuaKQ.Enabled = false;
                    //    btnXoaH1.Enabled = false;
                    //    btnXoaH2.Enabled = false;
                    //}
                    //else//chua qua ngay
                    //{
                    //    ptnButtonLXS.Enabled = true;
                    //    btnChupHinh.Enabled = true;
                    //    btnSuaKQ.Enabled = true;
                    //    btnXoaH1.Enabled = true;
                    //    btnXoaH2.Enabled = true;
                    //}
                    btnLuuKetQua.Enabled = false;
                    //set lai check cac loai benh
                    int IDBenhkq =0;
                    int IDBenh =-1;
                    int IDNhomkq =0;
                    int IDNhom =-1;
                    int idloaiBP = 0;
                    for (int i = 0; i < dtListBenh.Rows.Count; i++)
                    {                        
                        for (int j = 0; j < dt.Rows.Count; j++)
                        {
                            idloaiBP = int.Parse(dt.Rows[j]["LoaiBenhPham"].ToString());

                            IDBenh = int.Parse(dtListBenh.Rows[i]["IDBenh"].ToString());
                            IDBenhkq = int.Parse(dt.Rows[j]["IDBenh"].ToString());

                            IDNhom = int.Parse(dtListBenh.Rows[i]["IDNhomBenh"].ToString());
                            IDNhomkq = int.Parse(dt.Rows[j]["IDNhomBenh"].ToString());
                            if ((IDBenh == IDBenhkq) && (IDNhom == IDNhomkq))
                            {
                                dtListBenh.Rows[i]["Chon"] = 1;
                            }
                        }
                    }
                    //set lai ket luan
                    txtKetLuan1.Text = dt.Rows[0]["KetLuan"].ToString();
                    radLoaiBenhPham.EditValue = idloaiBP;
                    lan = 1;
                    isImg[0] = 1;
                    Xn.KQ1 = txtsotieuban.Text;
                    //control cho truong hop da co ket qua
                    btnSuaKQ.Visible = true;
                    btnCapnhat.Visible = false;
                    btnSuaKQ.Enabled = true;
                    //pnlKQ.Enabled = false;
                }
                else
                {
                    btnSuaKQ.Enabled = false;
                }
            }
            else//neu chua co ket qua
            {
                lan = 1;              
                txtKetLuan1.Text = "";
                btnLuuKetQua.Enabled = true;
                btnSuaKQ.Enabled = false;

                //btnSuaKQ.Visible = true;
                btnCapnhat.Visible = false;
                pnlKQ.Enabled = true;
                //set so tieu ban Pyy-XXXXX
                if(ByTB != 1)
                    txtsotieuban.Text = Xn.SoTieuBan;
            }
            gridConListBenh.DataSource = dtListBenh;
        }

        private void setDataToForm()
        {
            //load lai thong tin hanh chinh cua benh nhan
            loadTTHC();
            //load lai ket qua cho benh nhan
            loadKQ();           
        }
       
        private void LoadHinh(PictureEdit edit, ref Bitmap bm)
        {
            edit.Image = bm;
        }
        
        string path = "";
        private void LoadLaiHinhKQ(string lanthu, PictureEdit pic1, PictureEdit pic2
                                    , ref Bitmap Hinh1, ref Bitmap Hinh2)
        {
            string pathTemp_x100 = Application.StartupPath + "\\PictureTemp"  + "\\x100_" 
                                   + lanthu.ToString() + ".jpg";
            //x100
            if (File.Exists(pathTemp_x100))
            {
                if (!File.Exists(sThuMucLuu  + "\\x100_" + lanthu.ToString() + ".jpg"))
                {
                    File.Copy(pathTemp_x100, sThuMucLuu + "\\" 
                        + "\\x100_" + lanthu.ToString() + ".jpg");
                }
            }

            string pathHinhDaLuu_x100 = sThuMucLuu 
                + "\\x100_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathHinhDaLuu_x100))
            {
                Stream stream = File.Open(pathHinhDaLuu_x100, FileMode.Open,
                FileAccess.Read, FileShare.Delete);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();
                Hinh1 = m_Bitmap;
                LoadHinh(pic1, ref Hinh1);
            }
            else
            {
                Hinh1 = null;
                LoadHinh(pic1, ref Hinh1);
            }
            //x400
            string pathTemp_x400 = Application.StartupPath 
                + "\\PictureTemp"  + "\\x400_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathTemp_x400))
            {
                if (!File.Exists(sThuMucLuu + "\\x400_" + lanthu.ToString() + ".jpg"))
                {
                    File.Copy(pathTemp_x400, sThuMucLuu + 
                        "\\x400_" + lanthu.ToString() + ".jpg");
                }
            }

            string pathHinhDaLuu_x400 = sThuMucLuu + "\\x400_" + lanthu.ToString() + ".jpg";
            if (File.Exists(pathHinhDaLuu_x400))
            {
                Stream stream = File.Open(pathHinhDaLuu_x400, FileMode.Open,
                FileAccess.Read, FileShare.Delete);
                Bitmap m_Bitmap = (Bitmap)Bitmap.FromStream(stream);
                stream.Close();
                Hinh2 = m_Bitmap;
                LoadHinh(pic2, ref Hinh2);
            }
            else
            {
                Hinh2 = null;
                LoadHinh(pic2, ref Hinh2);
            }
        }
        
        private void LoadHinh()
        {
            //load lai hinh kq
            LoadLaiHinhKQ(txtsotieuban.Text, picCL1, picCL2, ref bmHinh1, ref bmHinh2);
        }
         
        private void frmKetQua_Load(object sender, EventArgs e)
        {
            try
            {
                radLoaiBenhPham.EditValue = 1;
                getPathStrHinh();
                CreateDir();
                CnPKham();
                if (ByTB != 1)
                {
                    setDataToForm();
                    ptnByTB.Visible = false;
                    txtsotieuban.Enabled = false;
                }
                //else
                //{
                    loadComboBox();
                //}
                LoadHinh();
                if (txtKetLuan1.Text != "")
                    flagKQ = 1;
                btngo_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }            
        } 

        void frm_thoatEven(object sender, object data)
        {
            LoadHinh();
            isImg = (int[])data;
        }

        private void btnChupHinh_Click(object sender, EventArgs e)
        {
            try
            {
                frmChupHinh frmHinh = new frmChupHinh(txtsotieuban.Text,0);
                frmHinh.sThuMucLuu = this.sThuMucLuu;
                frmHinh.thoatEven += new frmChupHinh.DelegeChupH(frm_thoatEven);
                frmHinh.sophieu = Xn.SoBN;
                
                frmHinh.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void ClearHinh(ref PictureEdit pic, ref Bitmap hinh)
        {
            if (hinh != null)
            {
                hinh.Dispose();
                hinh = null;
                pic.Image = null;
                pic.Refresh();                
            }            
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    DialogResult result = MessageBox.Show("Bạn Chưa lưu kết quả./n" +
                        " Bạn có muốn lưu kết quả không ?", "Thông báo", MessageBoxButtons.YesNo,
                        MessageBoxIcon.Warning);
                    if (result == DialogResult.Yes)
                    {
                        btnLuuKetQua_Click(sender, e);
                    }
                }
                ClearHinh(ref picCL1,ref bmHinh1);
                ClearHinh(ref picCL2, ref bmHinh2);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }          
        }

        private void CreateDir()
        {
            string goc = strPathHinh;
            DateTime dt;
            if (Xn != null)
                dt = Xn.NgayNhan;
            else
                dt = DateTime.Today;
            string namthang = dt.Year.ToString() + Uit.it_String.Right("0" + dt.Month.ToString(), 2);
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4));
            }
            if (!Directory.Exists(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4)))
            {
                Directory.CreateDirectory(goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4));
            }
            this.sThuMucLuu = goc + "\\" + namthang.Substring(0, 4) + "\\" + namthang.Substring(2, 4);
        }

        private bool CheckSave()
        {               
            if (txtKetLuan1.Text.Trim() == "")
            {
                ErrorProvider.SetError(txtKetLuan1, "Bạn phải nhập kết luận!");
                return false;
            }
            else
                ErrorProvider.ClearErrors();
            return true;
        }
   
        private void btnLuuKetQua_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckSave())
                {
                    this.ketqua = 1;
                    ///kiem tra ket qua truoc khi luu
                    ///set value ket qua                
                    kqPAP.SoBN = txtSoBN.Text;
                    kqPAP.SoHS = txtSoHS.Text;
                    kqPAP.SoTBan = txtsotieuban.Text;
                    kqPAP.KetLuan = txtKetLuan1.Text;
                    kqPAP.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                    kqPAP.IDKTV = int.Parse(comKTV.EditValue.ToString());
                    kqPAP.LoaiBenhPham = int.Parse(radLoaiBenhPham.EditValue.ToString());

                    kqPAP.Host = Uit.it_Computer.ComputerName().ToString();
                    kqPAP.UserName = UserDTO.LoginName.ToString();
                    kqPAP.CDate = DateTime.Today;
                    kqPAP.pDate = DateTime.Now; 
                   
                    Boolean rs = false;      
             
                    DataTable dtkq = new DataTable();
                    dtkq = (DataTable)gridConListBenh.DataSource;
                    DataTable dtChanges = dtkq.GetChanges(DataRowState.Modified);
                    if (dtChanges == null)
                    {
                        MessageBox.Show("Bạn phải chọn kết quả", "Thông báo");
                        return;
                    }
                    //insert master
                    rs = KQBUS.InsertKetQuaPAP(kqPAP); 
                    if (rs)
                    {
                        rs = false;
                        //insert detail
                        if (dtChanges != null)
                        {
                            int IDBenh =0;
                            int IDNhom =0;
                            for (int i = 0; i < dtChanges.Rows.Count; i++)
                            {
                                if (int.Parse(dtChanges.Rows[i]["Chon"].ToString())==1)
                                {
                                    IDBenh = int.Parse(dtChanges.Rows[i]["IDBenh"].ToString());
                                    IDNhom = int.Parse(dtChanges.Rows[i]["IDNhomBenh"].ToString());
                                    KQBUS.InsertKetQuaPAP_dtl(kqPAP.SoBN, IDBenh, IDNhom);
                                }
                            }
                        }
                        //apdate vao table xac nhan                     
                        rs = KQBUS.UpdateXacNhan(kqPAP.SoBN, kqPAP.SoTBan, 1);
                        KQBUS.UpdateFee(kqPAP.SoBN, kqPAP.SoHS, txtSoNVien.Text,true
                                    , int.Parse(lblLoaiBN.Text), lblDVCode.Text, conpk);
                        if (rs)
                        {
                            dataTran[0] = lan;
                            if (lan >= 1)
                                dataTran[1] = 1;
                        }                               
                        btnLuuKetQua.Enabled = false;
                        btnSuaKQ.Enabled = true;
                        pnlKQ.Enabled = false;
                                              
                        flagLuu = 1;
                        flagKQ = 1;                                              
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }           
        }

        private void btnInKQ_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ == 0)
                {
                    XtraMessageBox.Show("Chưa có kết quả!", "Thông báo");
                }
                else if (flagLuu == 1)
                {
                    rptKQPAP rptKQ = new rptKQPAP();
                    SerDataToReport(rptKQ);
                    rptKQ.Print();
                }
                else
                {
                    XtraMessageBox.Show("Chưa lưu kết quả!", "Thông báo");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void checkKQ(rptKQPAP rptKQ, DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int loaiBP = int.Parse(dt.Rows[i]["LoaiBenhPham"].ToString());
                int IDNhomBenh = int.Parse(dt.Rows[i]["IDNhomBenh"].ToString());
                int IDBenh = int.Parse(dt.Rows[i]["IDBenh"].ToString());
                if (loaiBP == 1)
                {
                    rptKQ.chknhungdich.Checked = true;
                }
                else
                {
                    rptKQ.chkthuongquy.Checked = true;
                }
                switch (IDNhomBenh)
                {
                    case 1:
                        switch (IDBenh)
                        {
                            case 2:
                                rptKQ.txt12.Checked = true;
                                break;
                            case 3:
                                rptKQ.txt13.Checked = true;
                                break;
                            case 4:
                                rptKQ.txt14.Checked = true;
                                break;
                            case 5:
                                rptKQ.txt15.Checked = true;
                                break;
                            case 6:
                                rptKQ.txt16.Checked = true;
                                break;
                            case 30:
                                rptKQ.txt30.Checked = true;
                                break;
                        }
                        break;
                    case 2:
                        switch (IDBenh)
                        {
                            case 7:
                                rptKQ.txt27.Checked = true;
                                break;
                            case 10:
                                rptKQ.txt210.Checked = true;
                                break;
                            case 11:
                                rptKQ.txt211.Checked = true;
                                break;
                            case 12:
                                rptKQ.txt212.Checked = true;
                                break;
                            case 13:
                                rptKQ.txt213.Checked = true;
                                break;
                            case 14:
                                rptKQ.txt214.Checked = true;
                                break;
                        }
                        break;
                    case 3:
                        switch (IDBenh)
                        {
                            case 20:
                                rptKQ.txt320.Checked = true;
                                break;
                            //case 21:
                            //    rptKQ.txt321.Checked = true;
                            //    break;
                            //case 22:
                            //    rptKQ.txt322.Checked = true;
                            //    break;
                            //case 23:
                            //    rptKQ.txt323.Checked = true;
                            //    break;
                            //case 24:
                            //    rptKQ.txt324.Checked = true;
                            //    break;
                            case 25:
                                rptKQ.txt325.Checked = true;
                                break;
                            case 26:
                                rptKQ.txt326.Checked = true;
                                break;
                            case 27:
                                rptKQ.txt327.Checked = true;
                                break;
                            case 28:
                                rptKQ.txt328.Checked = true;
                                break;
                            case 29:
                                rptKQ.txt329.Checked = true;
                                break;
                        }
                        break;
                    case 4:
                        switch (IDBenh)
                        {
                            case 15:
                                rptKQ.txt415.Checked = true;
                                break;
                            case 16:
                                rptKQ.txt416.Checked = true;
                                break;
                            case 17:
                                rptKQ.txt417.Checked = true;
                                break;
                            case 18:
                                rptKQ.txt418.Checked = true;
                                break;
                            case 19:
                                rptKQ.txt419.Checked = true;
                                break;
                            case 31:
                                rptKQ.txt31.Checked = true;
                                break;
                            case 32:
                                rptKQ.txt420.Checked = true;
                                break;
                        }
                        break;

                }
            }  
        }

        private int SerDataToReport(rptKQPAP rptKQ)
        {
            DateTime cdate = DateTime.Today, cdate2 = DateTime.Today;
            DataTable dt = KQBUS.GetKetQuaPAP(txtSoBN.Text,txtSoHS.Text);
            if (dt.Rows.Count > 0)
            {
                rptKQ.txtSoTieuBan.Text = dt.Rows[0]["SoTieuBan"].ToString().ToUpper();
                rptKQ.txtDiaChi.Text = dt.Rows[0]["DiaChi"].ToString();
                rptKQ.txtketluan.Text = dt.Rows[0]["KetLuan"].ToString();
                if (dt.Rows[0]["PTVien"].ToString() != "")
                {
                    combscd.EditValue = Convert.ToInt32(dt.Rows[0]["PTVien"].ToString());
                }
                else
                {
                    combscd.EditValue = 0;
                }
                rptKQ.txtbslaymau.Text = comPTVien.Text;
                rptKQ.txtDViChiDinh.Text = dt.Rows[0]["TenDViGuiMau"].ToString();
                checkKQ(rptKQ, dt);           
            }
            else
            {
                return 1;
            }
            string gioi = "";
            if (Xn.Gioi)
                gioi = "Nam";
            else
                gioi = "Nữ";
            
            rptKQ.barSoHS.Text = txtSoHS.Text;
            rptKQ.txtSoBN.Text = txtSoBN.Text;
            
            rptKQ.txthoten.Text = Xn.HoTen.ToUpper();
            rptKQ.txtGioiTinh.Text = gioi;
            rptKQ.txttuoi.Text = Xn.NamSinh.ToString()
                                + "(" + dt.Rows[0]["Tuoi"].ToString() + " Tuổi)";
            rptKQ.txtchuandoan.Text = Xn.ChuanDoan;
            rptKQ.txtngaylaymau.Text = Xn.NgayLayMau.ToString("dd/MM/yyyy");
            
            rptKQ.txtngaynhanmau.Text = Xn.NgayNhan.ToString("dd/MM/yyyy, hh:mm");
           
            if(txtKetLuan1.Text =="")
            {
                return 1;
            }                

            rptKQ.piclan1.Image = picCL1.Image;
            rptKQ.piclan2.Image = picCL2.Image;
            cdate = DateTime.Parse(dt.Rows[0]["CDate"].ToString());
            rptKQ.txttendv.Text = "Đơn Vị:";

            rptKQ.txtngaythang.Text = "Ngày " + cdate.Day.ToString("00") +
                                  " Tháng " + cdate.Month.ToString("00") +
                                  " Năm " + cdate.Year.ToString("0000");
          
            if (rptKQ.piclan1.Image == null)
            {
                rptKQ.piclan1.Visible = false;
            }
            if (rptKQ.piclan2.Image == null)
            {
                rptKQ.piclan2.Visible = false;
            }
            rptKQ.txtngaygioin.Text =DateTime.Now.ToString("dd/MM/yyyy, hh:mm:ss");
            rptKQ.txtbsthuchien.Text = comBacSi.Text;
            return 0;
        }

        private void btnPrintRevew_Click(object sender, EventArgs e)
        {
            try
            {
                if (flagKQ != 0 && flagLuu != 0)
                {
                    rptKQPAP rptKQ = new rptKQPAP();
                    int rs = SerDataToReport(rptKQ);
                    if (rs != 0)
                    {
                        MessageBox.Show("Bạn chưa nhập kết luận!", "Thông Báo");
                        return;
                    }
                    rptKQ.ShowPreviewDialog();               
                }
                else
                {
                    DevExpress.LookAndFeel.UserLookAndFeel lookAndFeel = new DevExpress.LookAndFeel.UserLookAndFeel(this);
                    XtraMessageBox.Show(lookAndFeel, "Chưa lưu kết quả.\nBạn phải lưu kết quả trước");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void frmKetQua_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thoatEven != null)
            {
                thoatEven(this, dataTran);
            }
        }
               
        /// <summary>
        /// xoa hinh kho xoa ket qua
        /// </summary>
        /// <param name="kqLan">hinh ket qua lan thu i</param>
        /// <param name="loaiHinh">loai hinh x100 hay x400</param>
        private void xoaHinh(ref PictureEdit picXoa, ref Bitmap hinhXoa
                            , string kqLan, string loaiHinh)
        {
            string urlServer = sThuMucLuu +"\\" + loaiHinh + "_" + kqLan + ".jpg";
            string urlLocal = Application.StartupPath + "\\PictureTemp"
                                   + "\\" + loaiHinh + "_" + kqLan + ".jpg";
            if (File.Exists(urlServer))
            {
                //clear hinh
                ClearHinh(ref picXoa, ref hinhXoa); 
                //xoa hinh
                File.Delete(urlServer);
            }
            if (File.Exists(urlLocal))
            {
                //clear hinh
                ClearHinh(ref picXoa, ref hinhXoa);
                //xoa hinh
                File.Delete(urlLocal);
            }
        }

        private void btnXoaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                //xoa database
                bool rs = KQBUS.DeleteKQPAP(txtSoBN.Text);

                if (rs)
                {
                    //xoa hinh
                    //xoaHinh(ref picCL1, ref bmHinh1, txtsotieuban.Text, "X100");
                    //xoaHinh(ref picCL2, ref bmHinh2, txtsotieuban.Text, "X400");
                    //xoa detail
                    bool rsdel = false;
                    rsdel = KQBUS.DeleteKQPAP_dtl(txtSoBN.Text);

                    //update xac nhan
                    bool kqup = false;
                    kqup = KQBUS.UpdateXacNhan(txtSoBN.Text, "0", 1);
                    if (kqup)
                    {
                        //dataTran[0]: lan ; dataTran[1]: 1=reload 0=No reload
                        dataTran[0] = 0;
                        dataTran[1] = 1;
                        flagLuu = 0;
                        flagKQ = 0;
                        btngo_Click(sender, e);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(),"Thông Báo");
            }           
        }

        private void btnSuaKQ_Click(object sender, EventArgs e)
        {
            try
            {
                flagLuu = 0;
                pnlKQ.Enabled = true;
                btnLuuKetQua.Enabled = false;
                btnSuaKQ.Visible = false;
                btnCapnhat.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void btnCapnhat_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckSave())
                {
                    kqPAP.SoBN = txtSoBN.Text;
                    kqPAP.KetLuan = txtKetLuan1.Text;
                    kqPAP.IDBacSiTH = int.Parse(comBacSi.EditValue.ToString());
                    kqPAP.IDKTV = int.Parse(comKTV.EditValue.ToString());
                    kqPAP.LoaiBenhPham = int.Parse(radLoaiBenhPham.EditValue.ToString());

                    kqPAP.Host = Uit.it_Computer.ComputerName().ToString();
                    kqPAP.UserName =UserDTO.LoginName.ToString();
                    kqPAP.CDate = DateTime.Today;
                    kqPAP.pDate = DateTime.Now; 
                    //kiem tra cho ke qua nao khong
                    DataTable dtListBenh = GetThongTinSearchBUS.GetDsBenhPAP();//ds cac benh
                    
                    //kiem tra luoi kq
                    DataTable dtkq = new DataTable();
                    dtkq = (DataTable)gridConListBenh.DataSource;
                    DataTable dtChanges = dtkq.GetChanges(DataRowState.Modified);
                    DataTable dtUnChanges = dtkq.GetChanges(DataRowState.Unchanged);
                    int numUncheck = 0;
                    for (int i = 0; i < dtChanges.Rows.Count; i++)
                    {
                        if (int.Parse(dtChanges.Rows[i]["Chon"].ToString()) == 0)
                        {
                            numUncheck++;
                        }
                    }
                    if (dtListBenh.Rows.Count == (dtUnChanges.Rows.Count + numUncheck))
                    {
                        MessageBox.Show("Bạn phải chon kế quả bệnh!!!", "Thông Báo");
                        frmKetQua_Load(sender, e);
                        btnCapnhat.Visible = false;
                        btnSuaKQ.Visible = true;
                        return;
                    }
                    else//update master
                    {
                        bool rsUpMas = false;
                        rsUpMas = KQBUS.UpdateKetQuaPAP(kqPAP);
                        if (rsUpMas == false)
                        {
                            MessageBox.Show("Cập nhật thất bại!!", "Thông Báo");
                            return;
                        }
                    }
                    //cap nhat cac ket qua detail
                    bool rsdel = false;
                    rsdel = KQBUS.DeleteKQPAP_dtl(txtSoBN.Text);
                    if (rsdel)
                    {                        
                        if (dtChanges != null)
                        {
                            bool rsins = true;
                            for (int i = 0; i < dtChanges.Rows.Count; i++)
                            {
                                if (int.Parse(dtChanges.Rows[i]["Chon"].ToString()) == 1)
                                {
                                    int IDBenh =int.Parse(dtChanges.Rows[i]["IDBenh"].ToString());
                                    int IDNhomBenh =int.Parse(dtChanges.Rows[i]["IDNhomBenh"].ToString());
                                    rsins &= KQBUS.InsertKetQuaPAP_dtl(txtSoBN.Text, IDBenh, IDNhomBenh);
                                }
                            }
                            if (rsins)
                            { 
                                btnSuaKQ.Visible = true;
                                btnCapnhat.Visible = false;
                                pnlKQ.Enabled = false;
                                flagLuu = 1;
                                flagKQ = 1;
                            }
                           
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void frmKetQua_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F2:
                    btnCapnhat_Click(sender, e);
                    break;
                case Keys.F3:
                    if (btnLuuKetQua.Enabled == true)
                    {
                        btnLuuKetQua_Click(sender, e);
                    }
                    break;
                case Keys.F4:
                    if (btnSuaKQ.Enabled == true)
                        btnSuaKQ_Click(sender, e);
                    break;
                case Keys.F9:
                    btnInKQ_Click(sender, e);
                    break;               
                case Keys.F12:
                    if (!txtsotieuban.Text.Trim().Equals(""))
                    {
                        btnNext_Click(sender, e);
                        SendKeys.Send("{TAB}");
                    }
                    break;
                case Keys.F11:
                    if (!txtsotieuban.Text.Trim().Equals("") && btnPrevious.Enabled == true)
                        btnPrevious_Click(sender, e);
                    break;
            }    
        }

        private void btnXoaH1_Click(object sender, EventArgs e)
        {
            try
            {
                xoaHinh(ref picCL1, ref bmHinh1, txtsotieuban.Text, "X100");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void btnXoaH2_Click(object sender, EventArgs e)
        {
            try
            {
                xoaHinh(ref picCL2, ref bmHinh2, txtsotieuban.Text, "X400");
            }
            catch (Exception ex)
            {
                MessageBox.Show("CH- " + ex.Message, "Thông Báo");
            }
        }

        private void txtKetLuan1_Leave(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.White;
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }

        private void txtKetLuan1_Enter(object sender, EventArgs e)
        {
            this.txtKetLuan1.Properties.Appearance.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(211)))));
            this.txtKetLuan1.Properties.Appearance.Options.UseBackColor = true;
        }
        
        /// <summary>
        /// Lay chuoi tu phai sang theo leng truyen vao
        /// </summary>
        /// <param name="value">chuoi can cat</param>
        /// <param name="length">chieu dai can cat</param>
        /// <returns>chuoi can cat</returns>
        public string Right(string value, int length)
        {
            return value.Substring(value.Length - length);
        }

        /// <summary>
        /// hàm lấy chuỗi từ trái sang
        /// </summary>
        /// <param name="value">giá trị của chuỗi cần cắt</param>
        /// <param name="length">chiều dài cảu chuỗi con</param>
        /// <returns>cuỗi cần lấy</returns>
        public string Left(string value, int length)
        {
            return value.Substring(0, length);
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            int numCur = 0, numPrev = 0;
            string pre = "";
            if (txtsotieuban.Text.ToUpper() == "P__-_____")
            {
                return;
            }
            else
            {
                numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengTeBao));
            }
            
            if (numCur <= 2)
                btnPrevious.Enabled = false;
            numPrev = numCur - 1;
            pre = Left(txtsotieuban.Text.ToUpper(), 4);
            txtsotieuban.Text = pre + numPrev.ToString("00000");

            btngo_Click(sender, e);         
        }

        private void btngo_Click(object sender, EventArgs e)
        {
            string SoTieuBan = txtsotieuban.Text;
            if (SoTieuBan.Equals(""))
                return;
            Xn = new TTXacNhanDTO();
            DataTable dt = GetThongTinSearchBUS.SearchDaXacNhanBySoTB(SoTieuBan);
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    txtSoHS.Text = dt.Rows[0]["SoHS"].ToString();
                    Xn.SoHS = txtSoHS.Text;
                    txtSoBN.Text = dt.Rows[0]["SoBN"].ToString();
                    Xn.SoBN = dt.Rows[0]["SoBN"].ToString();
                    txtSoNVien.Text = dt.Rows[0]["sonhapvien"].ToString();
                    Xn.SoNV = dt.Rows[0]["sonhapvien"].ToString();
                    txtHoTen.Text = dt.Rows[0]["HoTen"].ToString();
                    Xn.HoTen = dt.Rows[0]["HoTen"].ToString();
                    txtGioi.Text = dt.Rows[0]["gioi"].ToString();
                    Xn.Gioi = bool.Parse( dt.Rows[0]["GioiTinh"].ToString());
                    txtTuoi.Text = dt.Rows[0]["namsinh"].ToString()
                                 + "(" + dt.Rows[0]["tuoi"].ToString() + " Tuổi)";
                    Xn.NamSinh = int.Parse(dt.Rows[0]["namsinh"].ToString());
                    Xn.Tuoi = int.Parse(dt.Rows[0]["tuoi"].ToString());

                    txtDichVu.Text = dt.Rows[0]["tendvu"].ToString();
                    Xn.TenDVu = dt.Rows[0]["tendvu"].ToString();

                    txtNghe.Text = dt.Rows[0]["DienThoai"].ToString();
                    Xn.Nghe = dt.Rows[0]["Nghe"].ToString();   

                    txtDVChiDinh.Text = dt.Rows[0]["tendonvi"].ToString();
                    Xn.TenDViChiDinh = dt.Rows[0]["tendonvi"].ToString();

                    txtChuanDoan.Text = dt.Rows[0]["chandoan"].ToString();
                    Xn.ChuanDoan = dt.Rows[0]["chandoan"].ToString();

                    Xn.NgayLayMau = DateTime.Parse(dt.Rows[0]["ngaylaymau"].ToString());
                    Xn.NgayNhan = DateTime.Parse(dt.Rows[0]["ngaynhan"].ToString());
                    Xn.DVuCode = dt.Rows[0]["dvucode"].ToString();

                    lblDVCode.Text = Xn.DVuCode;
                    lblLoaiBN.Text = dt.Rows[0]["LoaiBN"].ToString();

                    comPTVien.EditValue = dt.Rows[0]["ptvid"].ToString();

                    comDonVi.EditValue = dt.Rows[0]["IDDViGuiMau"].ToString();

                    CreateDir();
                    flagKQ = 1;
                    flagLuu = 1;
                }
                else
                {
                    initControl(this);                   
                }
            }
            
            LoadHinh();
            loadKQ();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            int numCur = 0, numNext = 0;
            string pre = "";
            if (txtsotieuban.Text.ToUpper() == "P__-_____")
            {
                return;
            }
            else
            {
                numCur = int.Parse(Right(txtsotieuban.Text, hensu.LengTeBao));
            }
            
            if (numCur >= 1)
                btnPrevious.Enabled = true;
            numNext = numCur + 1;
           
            pre = Left(txtsotieuban.Text.ToUpper(), 4);
            txtsotieuban.Text = pre + numNext.ToString("00000");
           
            btngo_Click(sender, e);           
        }

        private void txtsotieuban_Validated(object sender, EventArgs e)
        {
            btngo_Click(sender, e);
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            frmKetQua_Load(sender, e);
        }
    }
}